<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索框 -->
    <van-search @input="changeContent" @search='handleSearch' v-model.trim="q" placeholder="请输入搜索关键词" shape="round" />
    <!-- 联想列表 -->
    <van-cell-group v-show="q" class="suggest-box">
      <van-cell @click="handleJump(index)" icon="search" v-for="item in newList" :key="item">
        <p v-html="item">{{item}}</p>
      </van-cell>
    </van-cell-group>
    <!-- 搜索历史 -->
    <div class="history-box" v-show="list.length&&!q">
      <div class="head">
        <span>历史记录</span>
        <van-icon @click="removeHistory" name="delete"></van-icon>
      </div>
      <van-cell-group>
        <van-cell v-for="(item,index) in list" :key="item">
          <router-link :to="'/result/'+ item">{{item}}</router-link>
          <a class="word_btn">{{item}}</a>
          <van-icon @click="deleteHistory(index)" class="close_btn" slot="right-icon" name="cross" />
        </van-cell>
      </van-cell-group>

    </div>
  </div>

</template>
<script>
import { changeContent } from '@/api/channel.js'
const SEARCH_KEY = 'search-history'
export default {
  data () {
    return {
      // 输入内容
      q: '',
      // 历史记录
      list: JSON.parse(localStorage.getItem(SEARCH_KEY)) || [],
      // 联想内容
      content: [],
      timer: null
    }
  },
  computed: {
    newList () {
      const reg = new RegExp(this.q, 'ig')
      return this.content.map(item => {
        return item.replace(reg, '<span>' + this.q + '</span>')
      })
    }
  },
  methods: {
    // 跳转
    handleJump (index) {
      // const reg = new RegExp('<span>' + this.q + '</span>', 'ig')
      // this.$router.push('/result/' + item.replace(reg, this.q))
      this.$router.push('/result/' + this.content[index])
    },
    removeHistory () {
      // 清空列表
      this.list = []
      // 清除本地缓存
      localStorage.removeItem(SEARCH_KEY)
    },
    // 根据索引值删除该项
    deleteHistory (index) {
      // 从历史列表中删除该项
      this.list.splice(index, 1)
      // 本地缓存刷新
      localStorage.setItem(SEARCH_KEY, JSON.stringify(this.list))
    },
    // 根据关键字获取联想列表
    changeContent () {
      try {
        window.clearTimeout(this.timer)
        this.timer = window.setTimeout(async (item, index) => {
          // 当搜索框是清空状态 就不发送请求
          if (!this.q) {
            return
          }
          const ret = await changeContent(this.q)
          // 获取到联想内容
          this.content = ret.data.options
          // 联想内容需要根据搜索内容进行高亮
          // q都要加一个span标签 让加标签的替换原本的样式
          // 需要进行不区分大小写 全局匹配
          // const reg = new RegExp(this.q, 'ig')
          // this.content = ret.data.options.map(item => {
          //   return item.replace(reg, `<span>${this.q}</span>`)
          // })
          // console.log(this.content)
        }, 300)
      } catch (error) {
        this.$toast.fail('查询数据失败')
      }
    },
    // 提交内容
    handleSearch () {
      // 把关键字添加到list中 但是会有重复问题 需要去重
      this.list.push(this.q)
      // 去重 利用es6中的Set()
      const a = new Set(this.list)
      this.list = [...a]
      // 将历史记录保存到本地缓存中
      localStorage.setItem(SEARCH_KEY, JSON.stringify(this.list))
      // console.log(this.list)
      // this.q = ''
      // 跳转
      this.$router.push('/result/' + this.q)
    }
  }
}
</script>
<style scoped lang='less'>
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}

.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
</style>
